package de.blitzcoder.collide.util;

import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import sun.misc.BASE64Encoder;

/*
 * This is a simple HTTP POST Implementation to send some Objects
 */

/**
 *
 * @author blitzcoder
 */
public class HttpPost extends Thread {

    private URL url;
    private HashMap<String,Object> data;

    public HttpPost(URL url,HashMap<String,Object> data) {
        this.url = url;
        this.data = data;

        if (!url.getProtocol().toLowerCase().equals("http"))
            throw new RuntimeException("Protocol has to be http");

        setName("HttpPost");
    }

    public void startConnection() {
        start();
    }

    public void run() {
        try {

            // Open the stream
            int port = url.getPort();
            if (port == -1)
                port = 80;
            System.out.println(port);
            Socket socket = new Socket(url.getHost(), port);
            PrintStream s = new PrintStream(socket.getOutputStream());

            // Prepare the POST-Part of the request
            String post = "";
            Object[] keys = data.keySet().toArray();
            BASE64Encoder base64encoder = new BASE64Encoder();
            for (Object keyObject:keys) {

                String key = (String)keyObject;
                post+="&"+key+"=";

                byte[] base64data;
                if (data.get(keyObject) instanceof byte[]) {
                    base64data = (byte[])data.get(keyObject);
                } else if (data.get(keyObject) instanceof String) {
                    base64data = ((String)data.get(keyObject)).getBytes();
                } else {
                    // Create two streams to serialize the object
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    ObjectOutputStream oos = new ObjectOutputStream(baos);

                    // Serialize and base64 the object
                    oos.writeObject(data.get(keyObject));
                    oos.close();

                    base64data = baos.toByteArray();
                }
                String base64 = base64encoder.encode(base64data);

                // Add object to the POST-String
                post+=URLEncoder.encode(base64,"UTF-8");

            }
            post = post.substring(1); // Cut the &

            String req = "";
            req+="POST "+url.getPath()+" HTTP/1.1\n";
            req+="Host: "+url.getHost()+"\n";
            req+="Content-Type: application/x-www-form-urlencoded"+"\n";
            req+="Content-Length: "+(post.length())+"\n";
            req+="\n";
            req+=post;
            req+="\n\n\n";

            s.print(req);
            s.close();

        } catch (Exception ex) {
            throw new Error(ex);
        }
    }

}
